package com.lbj.googleplay.googleplay100.manager;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//线程管理器
public class ThreadManager {

    public static ThreadPool mPool;

    public static ThreadPool getThreadPool(){

        if (mPool==null){
            synchronized (ThreadManager.class){
                if (mPool==null) {
                    //获取cpu数量
                    int cpuCount = Runtime.getRuntime().availableProcessors();
                    int threadCount = cpuCount*2+1;//线程个数
                    mPool = new ThreadPool(threadCount,threadCount,1L);
                }
            }
        }
        return mPool;
    }

    //线程池类
    public static class ThreadPool{

        private int corePoolSize;//核心线程数
        private int maximumPoolSize;//最大线程数
        private long keepAliveTime;//休息时长
        private ThreadPoolExecutor executor;//线程池执行器


        public ThreadPool(int corePoolSize,int maximumPoolSize,long keepAliveTime){
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;

        }

        public void execute(Runnable r){
            if (executor == null) {
                executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
            }
            //执行一个Runnable对象
            executor.execute(r);
        }

    }
}
